/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.lestr.udm.core2.managers.storage;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.lestr.udm.core2.DefaultDataManager;
import org.lestr.udm.core2.GdmException;
import org.lestr.udm.core2.IDataManager.ISession;
import org.lestr.udm.core2.StreamUtil;

/**
 *
 * @author pibonnin
 */
public class RamDataManager extends DefaultDataManager<RamDataManager.DefaultSession, DefaultDataManager.DefaultParameters> {

    private Map<String, byte[]> datas;

    public RamDataManager() {

        datas = new HashMap<String, byte[]>();

    }// END Constructor

    @Override
    public ISession openSession() throws GdmException {
        return new Session();
    }

    private class Session extends DefaultDataManager.DefaultSession {

        @Override
        public boolean addData(String id) throws GdmException {

            return datas.put(id, null) != null;

        }

        @Override
        public boolean existsData(String id) throws GdmException {

            return datas.containsKey(id);

        }

        @Override
        public boolean removeData(String id) throws GdmException {

            return datas.remove(id) != null;

        }

        @Override
        public boolean setDataValue(String id, InputStream value) throws GdmException {

            try {
                datas.put(id, StreamUtil.toByteArray(value));
            } catch (IOException ex) {
                Logger.getLogger(RamDataManager.class.getName()).log(Level.SEVERE, null, ex);
                throw new GdmException(ex);
            }

            return true;

        }

        @Override
        public InputStream getDataValue(String id) throws GdmException {

            return datas.containsKey(id) ? new ByteArrayInputStream(datas.get(id)) : null;

        }

        @Override
        public long getDataLength(String id) throws GdmException {

            return datas.get(id).length; 

        }
    }
}
